// API服务模块
const API_BASE_URL = 'http://192.168.19.138:7060'; // 远程服务器地址

// 创建axios实例
const request = async (url, options = {}) => {
  try {
    const response = await fetch(`${API_BASE_URL}${url}`, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('API请求失败:', error);
    throw error;
  }
};

// 获取在线视频列表
export const getSourceInfo = async () => {
  try {
    const response = await request('/source_info', {
      method: 'GET',
    });
    return response;
  } catch (error) {
    console.error('获取视频列表失败:', error);
    // 返回模拟数据用于测试
    return {
      code: '200',
      data: [
        {
          label: '火灾监控视频1',
          source: { value: 'http://example.com/fire1.mp4' },
          value: 1
        },
        {
          label: '交通事故视频',
          source: { value: 'http://example.com/traffic.mp4' },
          value: 2
        },
        {
          label: '工厂安全监控',
          source: { value: 'http://example.com/factory.mp4' },
          value: 3
        }
      ]
    };
  }
};

// 获取异常事件列表
export const getViewList = async (videoName = '') => {
  try {
    // 构建查询参数，使用正确的参数名file_name
    const params = videoName ? `?file_name=${encodeURIComponent(videoName)}` : '';
    console.log(`📡 调用view_list接口，参数: ${params}`);
    
    const response = await request(`/view_list${params}`, {
      method: 'GET',
    });
    
    console.log('✅ view_list接口响应:', response);
    return response;
  } catch (error) {
    console.error('获取异常事件列表失败:', error);
    console.log('🔄 使用模拟数据作为备用');
    
    // 返回模拟数据用于测试
    return {
      code: '200',
      data: [
        {
          create_time: '2024-01-15 10:30:25',
          description: '检测到异常火焰',
          event_id: 1001,
          event_name: '火灾检测',
          frame_no: 137,
          id: 1,
          level: 8.5,
          message_id: 101,
          summary: '在第137帧检测到异常火焰，疑似火灾发生',
          time: '2024-01-15 10:30:20'
        },
        {
          create_time: '2024-01-15 10:31:15',
          description: '检测到人员异常聚集',
          event_id: 1002,
          event_name: '人群异常检测',
          frame_no: 245,
          id: 2,
          level: 6.2,
          message_id: 102,
          summary: '在第245帧检测到人员异常聚集，可能存在安全隐患',
          time: '2024-01-15 10:31:10'
        },
        {
          create_time: '2024-01-15 10:32:45',
          description: '检测到物体异常移动',
          event_id: 1003,
          event_name: '物体移动检测',
          frame_no: 389,
          id: 3,
          level: 7.1,
          message_id: 103,
          summary: '在第389帧检测到物体异常移动，疑似物品被盗',
          time: '2024-01-15 10:32:40'
        }
      ]
    };
  }
};

export default {
  getSourceInfo,
  getViewList,
};